package io.adrainty.algorithm.leetcode.lcr;

/**
 * LCR 002. 二进制求和
 * @link <a href="https://leetcode.cn/problems/JFETK5/description/">...</a>
 * @author AdRainty
 * @version V1.0.0
 * @since 2024/8/29 上午12:09
 */
public class LCR002 {

    public String addBinary(String a, String b) {
        char[] aCharArray = a.toCharArray();
        char[] bCharArray = b.toCharArray();
        StringBuilder res = new StringBuilder();
        int al = aCharArray.length;
        int bl = bCharArray.length;

        int carry = 0;
        for (int i = al - 1, j = bl - 1; i >= 0 || j >= 0 || carry != 0; i--, j--) {
            int aNum = i >= 0 ? aCharArray[i] - '0' : 0;
            int bNum = j >= 0 ? bCharArray[j] - '0' : 0;
            int sum = aNum + bNum + carry;
            res.append(sum % 2);
            carry = sum/ 2;
        }

        return res.reverse().toString();
    }

}
